import React, { useState, useEffect, useCallback } from 'react';
import { Modal, Tabs, Descriptions, Timeline, Button, Spin, message,List } from 'antd';
import { UserOutlined, HistoryOutlined,MessageOutlined } from '@ant-design/icons';
import moment from 'moment';
import { Student, getStudentEvents, EventLog,getStudentEvaluations, Evaluation } from '@/utils/api/student/student';

const { TabPane } = Tabs;

interface StudentDetailModalProps {
    visible: boolean;
    onCancel: () => void;
    studentId: number | null;
    currentStudent: Student | null;
}

const StudentDetailModal: React.FC<StudentDetailModalProps> = React.memo(({
                                                                              visible,
                                                                              onCancel,
                                                                              studentId,
                                                                              currentStudent
                                                                          }) => {
    const [studentEvents, setStudentEvents] = useState<EventLog[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [activeTab, setActiveTab] = useState<string>('1');
    const [eventsLoaded, setEventsLoaded] = useState<boolean>(false);

    const [evaluations, setEvaluations] = useState<Evaluation[]>([]);
    const [evaluationsLoading, setEvaluationsLoading] = useState<boolean>(false);

    // 请求控制器ref，用于中断请求
    const abortControllerRef = React.useRef<AbortController | null>(null);

    // 获取学生事件日志
    const fetchStudentEvents = useCallback(async (id: number) => {
        // 中断之前的请求
        if (abortControllerRef.current) {
            abortControllerRef.current.abort();
        }

        // 创建新的AbortController
        const controller = new AbortController();
        abortControllerRef.current = controller;

        try {
            setLoading(true);
            const response = await getStudentEvents(id, { signal: controller.signal });

            // 检查请求是否被中止
            if (controller.signal.aborted) {
                return;
            }

            if (response.code === 200) {
                const events = Array.isArray(response.data) ?
                    response.data.map((event: any) => ({
                        ...event,
                        description: event.log
                    })) : [];
                setStudentEvents(events);
                setEventsLoaded(true);
            }
        } catch (error: any) {
            // 如果是中止请求的错误，不显示错误信息
            if (error.name === 'AbortError') {
                console.log('请求被中止');
                return;
            }
            console.error('获取学生事件日志失败:', error);
        } finally {
            setLoading(false);
        }
    }, []);

    // 获取评价记录的函数
    const fetchEvaluations = useCallback(async (id: number) => {
        try {
            setEvaluationsLoading(true);
            const response = await getStudentEvaluations(id);
            if (response.code === 200) {
                setEvaluations(response.data);
            }
        } catch (error) {
            console.error('获取评价记录失败:', error);
        } finally {
            setEvaluationsLoading(false);
        }
    }, []);

    // 处理标签页切换
    const handleTabChange = useCallback((key: string) => {
        setActiveTab(key);

        if (key === '2' && studentId && !eventsLoaded) {
            fetchStudentEvents(studentId);
        } else if (key === '3' && studentId) {
            // 切换到评价标签页时加载评价数据
            fetchEvaluations(studentId);
        }
    }, [studentId, eventsLoaded, fetchStudentEvents, fetchEvaluations]);

    // 当模态框关闭时重置状态
    useEffect(() => {
        if (!visible) {
            setActiveTab('1');
            setEventsLoaded(false);
            setStudentEvents([]);
        }

        // 清理函数：组件卸载时中止所有请求
        return () => {
            if (abortControllerRef.current) {
                abortControllerRef.current.abort();
            }
        };
    }, [visible]);

    return (
        <Modal
            title="学生详情"
            open={visible}
            onCancel={onCancel}
            footer={[
                <Button key="close" onClick={onCancel}>
                    关闭
                </Button>,
            ]}
            destroyOnClose={true}
            width={800}
        >
            <Spin spinning={loading}>
                {currentStudent && (
                    <Tabs activeKey={activeTab} onChange={handleTabChange}>
                        <TabPane
                            tab={
                                <span>
                                    <UserOutlined />
                                    基本信息
                                </span>
                            }
                            key="1"
                        >
                            <div style={{ padding: '20px' }}>
                                <Descriptions bordered column={2}>
                                    <Descriptions.Item label="学号" span={1}>
                                        {currentStudent.studentNumber || '-'}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="姓名" span={1}>
                                        {currentStudent.name}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="性别" span={1}>
                                        {currentStudent.sex === 0 ? '女' : '男'}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="年龄" span={1}>
                                        {currentStudent.age}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="出生日期" span={1}>
                                        {currentStudent.birthday ?
                                            moment(currentStudent.birthday).format('YYYY-MM-DD') :
                                            '-'}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="身份证号" span={2}>
                                        {currentStudent.idCard}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="手机号" span={1}>
                                        {currentStudent.phone}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="年级" span={1}>
                                        {currentStudent.grade ? `${currentStudent.grade}级` : '-'}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="院系" span={1}>
                                        {currentStudent.department || '-'}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="专业" span={1}>
                                        {currentStudent.major || '-'}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="所在小组" span={2}>
                                        {currentStudent.groupName || '无'}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="创建时间" span={2}>
                                        {currentStudent.createTime ?
                                            moment(currentStudent.createTime).format('YYYY-MM-DD HH:mm:ss') :
                                            '-'}
                                    </Descriptions.Item>
                                </Descriptions>
                            </div>
                        </TabPane>
                        <TabPane
                            tab={
                                <span>
                                    <HistoryOutlined />
                                    事件记录
                                </span>
                            }
                            key="2"
                        >
                            <div style={{ padding: '20px', maxHeight: '400px', overflowY: 'auto' }}>
                                <Timeline>
                                    {studentEvents.length > 0 ? (
                                        studentEvents.map((event, index) => (
                                            <Timeline.Item key={index}>
                                                <p>{event.log}</p>
                                                <p style={{ color: '#999', fontSize: '12px' }}>
                                                    {moment(event.createTime).format('YYYY-MM-DD HH:mm:ss')}
                                                </p>
                                            </Timeline.Item>
                                        ))
                                    ) : (
                                        <p>{eventsLoaded ? '暂无事件记录' : '点击加载事件记录...'}</p>
                                    )}
                                </Timeline>
                            </div>
                        </TabPane>

                        <TabPane
                            tab={
                                <span>
                                    <MessageOutlined />
                                        评价记录
                                </span>
                            }
                            key="3"
                        >
                            <div style={{ padding: '20px', maxHeight: '400px', overflowY: 'auto' }}>
                                <Spin spinning={evaluationsLoading}>
                                    {evaluations.length > 0 ? (
                                        <List
                                            itemLayout="vertical"
                                            dataSource={evaluations}
                                            renderItem={(item) => (
                                                <List.Item>
                                                    <List.Item.Meta
                                                        title={`来自 ${item.teacherName} 老师的评价`}
                                                        description={`评价时间: ${moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')}`}
                                                    />
                                                    <div style={{ marginTop: '10px' }}>{item.evaluation}</div>
                                                </List.Item>
                                            )}
                                        />
                                    ) : (
                                        <div style={{ textAlign: 'center', color: '#999', padding: '40px 0' }}>
                                            暂无评价记录
                                        </div>
                                    )}
                                </Spin>
                            </div>
                        </TabPane>
                    </Tabs>
                )}
            </Spin>
        </Modal>
    );
});

export default StudentDetailModal;